package com.neu.questionnaireplus.service.impl;

import com.neu.questionnaireplus.dao.TenementDao;
import com.neu.questionnaireplus.dao.UserDao;
import com.neu.questionnaireplus.entity.Tenement;
import com.neu.questionnaireplus.entity.User;
import com.neu.questionnaireplus.service.UserService;
import com.neu.questionnaireplus.utils.FileToUsers;
import com.neu.questionnaireplus.utils.common.CommonUtils;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.multipart.MultipartFile;

@Validated
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private TenementDao tenementDao;

    @Override
    public User queryUserByUsername(String username) {
        return userDao.queryUserByUsername(username);
    }

    @Override
    public List<User> queryUser() {
        return userDao.queryUser();
    }

    @Override
    public List<User> queryExistUser() {
        return userDao.queryExistUser();
    }

    @Override
    public List<User> queryUserByTenement(String belongTenement) {
        return userDao.queryUserByTenementName(belongTenement);
    }

    @Override
    public List<User> selectUserList(User user) {
        return userDao.selectUserList(user);
    }

    @Override
    public User queryUserByID(String id) {
        return userDao.queryUserByID(id);
    }

    @Transactional
    @Override
    public boolean insertUser(User user) {
        if (user != null && !user.getId().equals("")){
            try {
                String username = user.getUsername();
                String telnumber = user.getTelnumber();
                if (userDao.queryUserByPhone(telnumber) != null){
                    throw new RuntimeException("用户电话已存在");
                } else if (userDao.queryUserByUsername(username) != null) {
                    throw new RuntimeException("用户名已存在");
                }else if (tenementDao.queryTenementByUsername(user.getBelongTenement()) == null){
                    throw new RuntimeException("租户名不存在，请和你的租户确认好");
                } else {
                    int i = userDao.insertUser(user);
                    if (i == 1) return true;
                    else throw new RuntimeException("插入用户失败！！" + user);
                }
            }catch (Exception e){
                throw new RuntimeException("插入用户失败！！" + e.getMessage());
            }
        }else {
            throw new RuntimeException("插入用户失败,用户id不能为空");
        }
    }
    @Transactional
    @Override
    public boolean updateUser(User user) {
        if (user != null && !user.getId().equals("")){
            try {
                String username = user.getUsername();
                String telnumber = user.getTelnumber();
                User user1 = userDao.queryUserByPhone(telnumber);
                User user2 = userDao.queryUserByUsername(username);
                if ((user1 != null || user2 != null) && ( (user1 != null && !user.getId().equals(user1.getId())) || (user2 != null && !user.getId().equals(user2.getId()))) ){
                    throw new RuntimeException("修改的用户名或手机号与其他用户有冲突");
                }else {
                    int i = userDao.updateUser(user);
                    if (i == 1) return true;
                    else throw new RuntimeException("更新用户失败！！" + user);
                }
            }catch (Exception e){
                throw new RuntimeException("更新用户失败！！" + e.getMessage());
            }
        }else {
            throw new RuntimeException("更新用户失败,用户id不能为空");
        }
    }

    @Transactional
    @Override
    public boolean deleteUser(String id) {
        if (id != null && !id.equals("")){
            try {
                int i = userDao.deleteUser(id);
                if (i == 1) return true;
                else throw new RuntimeException("删除用户失败！！" + id);
            }catch (Exception e){
                throw new RuntimeException("删除用户失败！！" + e.getMessage());
            }
        }else {
            throw new RuntimeException("删除用户失败,用户id不能为空");
        }
    }

    @Override
    public User queryUserByPhone(String telnumber) {
        if (telnumber != null && !telnumber.equals("")){
            User t = null;
            t = userDao.queryUserByPhone(telnumber);
            if (t == null){
                throw new RuntimeException("未查询到该电话号码的用户");
            }else {
                return t;
            }
        }else {
            throw new RuntimeException("电话号码为空！！");
        }
    }

    @Override
    public boolean loginByPassword(String username, String password) {
        User t = null;
        t = userDao.queryUserByUsername(username);
        if (t == null){
            throw new RuntimeException("用户名不存在");
        }else {
            if (t.getPassword().equals(password)){
                if(t.getDelFlag() == 1 || t.getStatus() == 1){
                    throw new RuntimeException("账户被冻结或已经被删除请联系管理员");
                }else {
                    t.setLastLoginDate(CommonUtils.getDateByDateString(CommonUtils.getFormatDateTimeNow()));
                    boolean res = updateUser(t);
                    return res;
                }
            }else {
                throw new RuntimeException("密码错误");
            }
        }
    }

    @Override
    public boolean checkSecurityQuestion(String username,String answer) {
        User t = null;
        t = userDao.queryUserByUsername(username);
        if (t == null){
            throw new RuntimeException("用户名不存在");
        }else {
            if (t.getSecurityQuestionAnswer().equals(answer)){
                return true;
            }else {
                throw new RuntimeException("密保验证错误");
            }
        }
    }

    @Override
    public boolean hasDataRelation(String id) {
        //todo 查询用户创建的问卷是否还在进行中，进行中则具有数据关联
        return false;
    }

    @Override
    public List<User> queryUserByName(String username) {
        return userDao.queryUserByName(username);
    }

    @Transactional
    @Override
    public boolean forbiddenUser(String id) {
        User t = null;
        t = userDao.queryUserByID(id);
        if (t == null){
            throw new RuntimeException("用户不存在");
        }else {
            if (t.getStatus() == 1){//表示已经被冻结
                throw new RuntimeException("用户已经被冻结不可重复冻结");
            }else {
                t.setStatus(1);
                int flag = userDao.updateUser(t);
                if (flag == 1){
                    return true;
                }else {
                    throw new RuntimeException("冻结用户失败");
                }
            }
        }
    }

    @Transactional
    @Override
    public boolean freeUser(String id) {
        User t = null;
        t = userDao.queryUserByID(id);
        if (t == null){
            throw new RuntimeException("用户不存在");
        }else {
            if (t.getStatus() == 0){//表示未被冻结
                throw new RuntimeException("用户未处于冻结状态无需解冻用户");
            }else {
                t.setStatus(0);
                int flag = userDao.updateUser(t);
                if (flag == 1){
                    return true;
                }else {
                    throw new RuntimeException("解冻用户失败");
                }
            }
        }
    }

    @Transactional
    @Override
    public boolean modifyUserInfo(User user) {
        String id = user.getId();
        if (userDao.queryUserByID(id) != null){
            if (hasDataRelation(id)){
                throw new RuntimeException("该用户正在服务一些群组，不可修改信息");
            }else {
                int flag = userDao.updateUser(user);
                if (flag == 1){
                    return true;
                }else {
                    throw new RuntimeException("修改失败");
                }
            }
        }else {
            throw new RuntimeException("用户不存在");
        }
    }

    @Transactional
    @Override
    public boolean deleteUserInfo(User user) {
        String id = user.getId();
        if (userDao.queryUserByID(id) != null){
            if (hasDataRelation(id)){//查询是否有数据关联
                throw new RuntimeException("该用户正在服务一些群组，不可删除该用户");
            }else {
                user.setDelFlag(1);
                int flag = userDao.updateUser(user);
                if (flag == 1){
                    return true;
                }else {
                    throw new RuntimeException("删除失败");
                }
            }
        }else {
            throw new RuntimeException("用户不存在");
        }
    }

    @Override
    public List<User> importFileToUsers(Tenement tenement, MultipartFile file) throws RuntimeException {
        List<User> list = FileToUsers.importExcel(tenement,file);
        for (User user : list){
            insertUser(user);
        }
        return list;
    }

    @Override
    public boolean loginByPhone(String phone, String inputStr, String realStr) {
        User user = userDao.queryUserByPhone(phone);
        if (user != null){
            if (user.getStatus() == 1 || user.getDelFlag() == 1){
                throw new RuntimeException("该用户被冻结或被删除");
            }else {
                if (inputStr.equals(realStr)){
                    return true;
                }else {
                    throw new RuntimeException("手机验证码不正确");
                }
            }
        }else {
            throw new RuntimeException("该手机号下的用户不存在！");
        }
    }

    @Override
    public boolean checkRegisterStr(String phone, String inputStr, String realStr) {
        User user = userDao.queryUserByPhone(phone);
        if (user == null){
//      System.out.println(inputStr + " " + realStr);
            if (inputStr.equals(realStr)){
                return true;
            }else {
                throw new RuntimeException("手机验证码不正确");
            }
        }else {
            throw new RuntimeException("已经存在该用户，同一个手机号不能重复注册");
        }
    }

    @Override
    public boolean checkResetPwdStr(String phone, String inputStr, String realStr) {
        User user = userDao.queryUserByPhone(phone);
        if (user != null){
            if (inputStr.equals(realStr)){
                return true;
            }else {
                throw new RuntimeException("手机验证码不正确");
            }
        }else {
            throw new RuntimeException("该手机号下的用户不存在！");
        }
    }
}
